<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE HTML>
<html lang="zh">
<head>
	<%@include file="/WEB-INF/jsp/common/header.jsp"%>
    <script src="<%=request.getContextPath()%>/resources/jquery-file-upload/js/vendor/jquery.ui.widget.js" type="text/javascript"></script>
    <script src="<%=request.getContextPath()%>/resources/jquery-file-upload/js/jquery.fileupload.js" type="text/javascript"></script>
    <style type="text/css">
		.input-group-addon:not(.auto){width:90px;}
		#editModal input:not(.auto){width:450px;}
		#editModal textarea{width:450px;}
        .input-group {
            position: relative;
            display: table;
            border-collapse: separate;
        }
		.thumbnail{
			width: 100px;
			height: 100px;
		}
	</style>
</head>
<body>
<div class="container-fluid" style="padding-top: 10px;">
	<button id="add" type="button" class="btn btn-info" onclick="addProduct()">新增</button>
	<br />
	<form id="form" class="form-inline" role="form" action="#" method="get" style="padding-top: 10px;">
		<div class="form-group">
			<div class="input-group">
				<span class="input-group-addon">名称</span>
				<input type="text" class="form-control" id="product_name" value="" placeholder="产品名称" style="width: 130px;">
			</div>
            <div class="input-group">
                <span class="input-group-addon">状态</span>
                <select id="status_select" class="form-control">
                    <option value="" selected>全部</option>
                    <option value="0">下架</option>
                    <option value="1">上架</option>
                </select>
            </div>
			<button type="button" class="btn btn-primary" onclick="searchTable()">查询</button>
			<button type="button" class="btn btn-default" id="resetForm">清空</button>
		</div>
	</form>
	<br />
	<div>
		<table class="table table-hover table-striped table-bordered" style="table-layout:fixed;" id="productListTable"></table>
	</div>
</div>

<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-hidden="true">
	<div class="modal-dialog modal-lg" style="width: 600px;">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal">
					<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
				</button>
				<h4 class="modal-title" id="modalTitle">编辑产品</h4>
			</div>
			<div class="modal-body">
				<form id="editForm">
					<input type="hidden" name="id">
					<table id="editTable" class="table table-bordered">
						<tr>
							<td>
								<div class="input-group">
									<span class="input-group-addon">产品名称</span> <input type="text" class="form-control" name="name" placeholder="商品名称">
								</div>
								<input type="hidden" id="typeIdInput" name="typeId" value="${productType.id}">
							</td>
						</tr>
						<tr>
							<td>
								<img id="picImg" src="${pageContext.request.contextPath}/resources/img/icon-upload.png" id="picImg" class="thumbnail" onclick="selectUploadFile()">
								<input type="hidden" id="hiddenPicInput" name="picUrl">
								<div class="contextual-progress" id="progress" style="display: none;">
									<div class="progress">
										<div class="progress-bar progress-bar-info" style="width: 0%"></div>
									</div>
								</div>
								<input type="file" id="hiddenFileInput" style="display: none;">
							</td>
						</tr>
						<tr>
							<td>
								<div class="input-group">
									<span class="input-group-addon">价格($)</span> <input type="text" class="form-control" name="inputPrice" placeholder="价格">
                                    <input type="hidden" id="editPriceHidden" name="price">
								</div>
							</td>
						</tr>

						<tr>
							<td>
								<div class="input-group">
									<span class="input-group-addon">产品详情</span>
									<textarea class="form-control" name="remark" rows="3" placeholder="商品详情"></textarea>
								</div>
							</td>
						</tr>
						<tr>
							<td>
								<div class="input-group">
									<span class="input-group-addon">产品状态</span>
									<select name="status" class="form-control">
										<option value="1">上架</option>
										<option value="0">下架</option>
									</select>
								</div>
							</td>
						</tr>
						<tr>
							<td align="center">
								<button id="btn_submit" type="button" class="btn btn-success" style="width: 100px;">保存</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
								<button type="button" class="btn btn-danger" style="width: 100px;" data-dismiss="modal">关闭</button>
							</td>
						</tr>
					</table>
				</form>
			</div>
		</div>
	</div>
</div>
<script type="text/javascript">
	var productListTable;
    $(document).ready(function(){
        $("#resetForm").click(function(){
            $("#form input").val("");
        });

        $("#btn_submit").click(function() {
            var id = $("#editModal input[name=id]").val();
            var name = $("#editModal input[name=name]").val();
            var inputPrice = $("#editModal input[name=inputPrice]").val();
            var remark = $("#editModal textarea[name=remark]").val();
            var type_id = $("#editModal select[name=typeId]").val();
            var format = $("#editModal input[name=format]").val();
            var reg = /^[0-9]+(.[0-9]{1,2})?$/;
            if (name === "") {
                $.messager.alert("商品名不能为空");
                return false;
            }
            if (inputPrice === "" || !reg.test(inputPrice)) {
                $.messager.alert("价格不能为空且必须是数字，最多保留2位小数");
                return false;
            }
            $('#editPriceHidden').val((parseFloat(inputPrice) * 100).toFixed(0));
            $(this).attr("disabled","disabled");
            var url = contextpath + "/web/product/insert";
            if(id != null && id !== ""){
                url = contextpath + "/web/product/update";
            }
            $.ajax({
                type : "POST",
                url : url,
                data : $('#editForm').serialize(),
                success : function(result) {
                    $("#btn_submit").removeAttr("disabled");
                    if (result.code === 200) {
                        productListTable.ajax.reload();
                        $('#editModal').modal('hide')
                        $.messager.alert("提示", "保存成功");
                    } else {
                        $.messager.alert(result.msg);
                    }
                },
                error:function(){
                    $("#btn_submit").removeAttr("disabled");
                    $.messager.alert("提示", "保存失败，请检查网络");
                }
            });
        });

        productListTable = $('#productListTable').DataTable({
            "bSort": true, //是否启动各个字段的排序功能
			"aaSorting": [[3, "desc"]], //默认的排序方式
            "aoColumns": [
                {
                    "mDataProp": "name",
                    "sTitle":"名称",
                    "sDefaultContent": "--",
                    "sWidth": "20%",
                    "sClass": "center flow",
                    "bSortable": false,//是否支持排序
                    "bSearchable" : true,//是否支持条件查询
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        if(sData !== '--') $(nTd).attr('title', sData);
                    }
                },
                {
                    "mDataProp": "price",
                    "sTitle":"价格($)",
                    "sDefaultContent": "--",
                    "sWidth": "20%",
                    "sClass": "center flow",
                    "bSortable": false,//是否支持排序
                    "bSearchable" : false,//是否支持条件查询
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        if(sData !== '--') {
                            $(nTd).html((sData/100).toFixed(2) + "元");
						}
                    }
                },
                {
                    "mDataProp": "status",
                    "sTitle": "状态",
                    "sWidth": "15%",
                    "sDefaultContent": "--",
                    "bSortable": false,
                    "sClass": "center flow",
                    "bSearchable": false,//是否支持条件查询
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        if (sData === 1) $(nTd).html('上架').attr('title', '上架');
                        else $(nTd).html('下架').attr('title', '下架');
                    }
                },
                {
                    "mDataProp": "createTime",
                    "sTitle": "创建时间",
                    "sWidth": "15%",
                    "sDefaultContent": "--",
                    "bSortable": true,
                    "sClass": "center flow",
                    "bSearchable": false,//是否支持条件查询
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        if (sData !== '--') $(nTd).attr('title', sData);
                    }
                },
                {
                    "mDataProp": "id",
                    "sTitle": "操作",
                    "sWidth": "120px",
                    "sClass": "center flow",
                    "bSearchable": false,
                    "bSortable": false,
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        $(nTd).html("<a class='btn btn-xs btn-default' href='javascript:void(0);' onclick='editProduct(" + iRow + ")'><i class='fa fa-pencil'></i>&nbsp;编辑</a> &nbsp;")
                            .append("<a class='btn btn-xs btn-default' href='javascript:void(0);' onclick='deleteProduct(" + iRow + ")'><i class='fa fa-times'></i>&nbsp;删除</a>");
                    }
                }
            ],
            "ajax": {
                url: contextpath + '/web/product/queryPage',
                type:"post",
                data: function(data){
                    $.xDataTablesParams(data, $.trim($('#product_name').val()));
                    data['search.typeId'] = '${productType.id}';
                    data['search.status'] = $('#status_select').val();
                    return data;
                }
            }
        });

        $('#editModal').on('hide.bs.modal', function () {
            $("#btn_submit").removeAttr('disabled');
            $('#editForm :input').val('');
            $('#typeIdInput').val('${productType.id}');
            $('#picImg').attr('src', '${pageContext.request.contextPath}/resources/img/icon-upload.png');
        });

        //上传图片
        $("#hiddenFileInput").change(function(){
            $('#uploadProgressDlg').modal('show');
            $('#progress').show();
        });
        //图片上传
        $("#hiddenFileInput").fileupload({
            url : contextpath + '/web/upload/uploadFile',
            dataType: 'json',
            formData : function(form){
                return []
            },
            done: function (e, data) {
                $('#uploadProgressDlg').modal('hide');
                var file = data.files[0];
                console.log(data.result);
                if(data.result.code !== 200){
                    $.messager.alert("提示", "图片上传不成功");
                    return;
                }
                $("#hiddenPicInput").val(data.result.data.path);
                $('#picImg').attr('src', data.result.data.server + data.result.data.path);

                $('#uploadProgressDlg .progress-percentage').text("-- KB");
                $('#uploadProgressDlg .progress-bar').css('width', '0%');
                $('#progress').hide();
                $('#progress .progress-bar').css('width', '0%');
            },
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#uploadProgressDlg .progress-percentage').text(data.loaded/1000 + "/" + data.total/1000 + " KB");
                $('#uploadProgressDlg .progress-bar').css('width', progress + '%');
                $('#progress .progress-bar').css('width', progress + '%');
            }
        }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');

    });

    function searchTable(){
        productListTable.ajax.reload();
    }

    function editProduct(row){
        $('#modalTitle').text('编辑服务');
        var rowData = productListTable.row(row).data();
        $('#editModal :input[name=id]').val(rowData.id);
        $('#editModal :input[name=name]').val(rowData.name);
        $('#editModal :input[name=inputPrice]').val((rowData.price/100).toFixed(2));
        $('#editModal :input[name=price]').val(rowData.price);
        $('#editModal :input[name=picUrl]').val(rowData.picUrl);
        $('#editModal :input[name=remark]').val(rowData.remark);
        if(!rowData.picUrl || rowData.picUrl === ''){
            $('#picImg').attr('src', '${pageContext.request.contextPath}/resources/img/icon-upload.png');
        }else{
            $('#picImg').attr('src', '${fileViewServer}' + rowData.picUrl);
        }

        $("#editModal :input[name=status]").val(rowData.status);

        $('#editModal').modal('show');
    }

    function addProduct(){
        $('#modalTitle').text('新增服务');
        $('#editModal').modal('show');
    }

    function deleteProduct(row){
        var rowData = productListTable.row(row).data();
        $.messager.confirm("确定", "真的要删除'" + rowData.name + "'吗？", function(){
            $.ajax({
                url : contextpath + '/web/product/delete/' + rowData.id,
                type : 'DELETE',
                success :  function(data){
                    if (data.code === 200) {
                        $.messager.alert("提示", "删除成功");
                        productListTable.ajax.reload();
                    } else {
                        $.messager.alert(data.msg);
                    }
                }
            });
        });
    }

    /**
     *
     * @param index
     */
    function selectUploadFile(){
        $('#hiddenFileInput').click();
    }
</script>
</body>